import re
import configparser
import os
import pymongo
import common.gyblog as log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")
CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'
# 读取配置
cf = configparser.ConfigParser()
cf.read(os.path.dirname(os.path.abspath('.')) + '/download_javbook/config.ini')
DATA_BASE = cf.get('javbook', 'DATA_BASE')
DB_COL = cf.get('javbook', 'DB_COL')
SERIES = cf.get('javbook', 'SERIES')
YEAR = cf.get('javbook', 'YEAR')

'''
抓取tor优先级：
[ThZu.Cc] > [Thz.la]
1080p > 720p
'''


def get_nums():
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    query = {'series': SERIES, 'year': YEAR}
    projection = {'_id': 0, 'num': 1}
    nums = list(db_col.find(query, projection))
    db_client.close()
    print(len(nums))
    return nums


def save_tor(num):
    # 信任链接
    # url = 'https://sukebei.nyaa.si/?f=2&c=0_0&q={}-10MU'.format(num)
    url = 'https://sukebei.nyaa.si/?f=0&c=0_0&q=%5BUncensored%5D+10musume+{}'.format(num)
    # 创建 WebDriver 对象
    driver = webdriver.Chrome(service=SERVICE)
    driver.get(url)
    # 使用 XPath 定位元素
    elements = driver.page_source
    tors = re.findall("magnet:\?xt=urn:.*?&amp", elements)

    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    if len(tors) == 0:
        print('{}：没有找到tor'.format(url))
        LOG.info('{}：没有找到tor'.format(url))
    else:
        query = {'series': SERIES, 'num': num}
        new_values = {"$set": {"tor": tors[0], 'tor_name': 'subebei'}}
        db_col.update_one(query, new_values)
        print('已插入tor in {}'.format(url))
        LOG.info('已插入tor in {}'.format(url))
    driver.close()
    db_client.close()


def seek_subebei_by_num(num):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]
    # 查询
    query = {'series': SERIES, 'num': num}
    projection = {'_id': 0, 'tor': 1}
    query_ans = list(db_col.find(query, projection))
    # 关闭数据库连接
    db_client.close()
    # 结果处理
    if len(query_ans) == 1:
        if query_ans[0]['tor'] == '':
            save_tor(num)
        else:
            print('{}已有磁力，跳过'.format(num))
            LOG.info('{}已有磁力，跳过'.format(num))
    elif len(query_ans) == 0:
        print('在数据库中没有搜到：{}'.format(num))
        LOG.info('在数据库中没有搜到：{}'.format(num))
    else:
        print('在数据库中搜到多个：{}'.format(num))
        LOG.info('在数据库中搜到多个：{}'.format(num))
    db_client.close()


def query_tor_by_names(names):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    ans = []
    error_ans = []

    for name in names:
        # 查询
        query = {'series': SERIES, 'num': name}
        projection = {'_id': 0, 'tor': 1}
        query_ans = list(db_col.find(query, projection))
        if query_ans[0]['tor'] == '':
            error_ans.append(name)
        else:
            ans.append(query_ans[0]['tor'])
    print('搜索到的磁力：')
    for a in ans:
        if a != '':
            print(a)
    print('未搜索到的番号：')
    for e in error_ans:
        print(e)
    print('共{}个，{}有tor,{}没有'.format(len(names), len(ans), len(error_ans)))
    db_client.close()


if __name__ == '__main__':
    nums = get_nums()
    print(nums)
    for num in nums:
        seek_subebei_by_num(num['num'])

    # query_tor_by_names(nums)
